package at.fhooe.mc.master.clc.client;

import at.fhooe.mc.master.clc.client.widget.MessageBox;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.corechart.LineChart;
import com.mvp4g.client.Mvp4gModule;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class DatastoreMetrics implements EntryPoint
{

	private AuthenticationServiceAsync authenticationService = GWT.create(AuthenticationService.class);
	
	private void redirectToLogin(String login)
	{
		Window.Location.replace(login);
	}
	
	private void init()
	{
		Runnable onLoadCallback = new Runnable()
		{
			
			@Override
			public void run()
			{
				Mvp4gModule module = (Mvp4gModule)GWT.create( Mvp4gModule.class );
				module.createAndStartModule();
				RootLayoutPanel.get().add((Widget)module.getStartView());
			}
		};
		
		VisualizationUtils.loadVisualizationApi(onLoadCallback, LineChart.PACKAGE);
	}
	
	@Override
	public void onModuleLoad()
	{	
		// try to authenticate first
		authenticationService.authenticate(new AsyncCallback<String>()
				{
					
					@Override
					public void onSuccess(String result)
					{
						if (result.equals("OK"))
						{
							init();
						}
						else if (result.equals("NO_PERMISSION"))
						{
							MessageBox b = new MessageBox("Permission Error");
							b.setMessage("You don't have the permission to access this page!");
							b.center();
							return;
						}
						else
							redirectToLogin(result);
					}
					
					@Override
					public void onFailure(Throwable caught)
					{
						MessageBox b = new MessageBox("Error");
						b.setMessage("Error: Could not call authentication service.");
						b.center();
					}
		});
		
	}
}
